package com.apestech.framework.json;

import java.util.ArrayList;
import java.util.Date;

/**
 * @author hup
 * @create 2018-12-14-15:59
 */
public class JSONOrder {
    private JSONObject json=new JSONObject();
    private ArrayList<String> keylist=new ArrayList<String>();

    public JSONOrder(){}

    public JSONOrder(JSONOrder json){
        if(json==null) return;
        this.json=json.getJson();
        this.keylist=json.getOrderKeylist();
    }

    public void put(String key, Object value){
        if(json.get(key)==null){
            keylist.add(key);
        } else {
            int inx=getKeyIndex(key);
            keylist.set(inx, key);
        }
        json.put(key, value);
    }

    public void putAll(JSONOrder data){
        if(data==null) return;
        ArrayList<String> klist=data.getOrderKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String key=klist.get(i);
            json.put(key, data.get(key));
        }
    }

    public void addBefore(String inskey, String key, Object value) throws Exception {
        if(json.get(inskey)==null) throw new Exception("要插入的key值["+inskey+"]必须在map里存在！");
        int inx=getKeyIndex(inskey);
        if(json.get(key)!=null) remove(key);
        json.put(key, value);
        keylist.add(inx, key);
    }

    public void addAfter(String inskey, String key, Object value) throws Exception {
        if(json.get(inskey)==null) throw new Exception("要插入的key值["+inskey+"]必须在map里存在！");
        int inx=getKeyIndex(inskey);
        if(json.get(key)!=null) remove(key);
        json.put(key, value);
        if(keylist.size()-1==inx) keylist.add(key);
        else keylist.add(inx+1, key);
    }

    public int getKeyIndex(String key){
        int len=keylist.size();
        for(int i=0; i<len; i++){
            if(key.equals(keylist.get(i))) return i;
        }
        return -1;
    }

    public void remove(String key) throws Exception {
        json.remove(key);
        int inx=getKeyIndex(key);
        keylist.remove(inx);
    }

    public String getString(String key){
        return json.getString(key);
    }

    public String getFirstKey(){
        return json.getFirstKey();
    }

    public Object get(String key){
        return json.get(key);
    }

    public int getInteger(String key) throws Exception {
        return json.getIntValue(key);
    }

    public Date getDate(String key) throws Exception {
        return json.getDate(key);
    }

    public ArrayList<String> getKeylist(){
        return json.getKeylist();
    }

    public ArrayList<String> getOrderKeylist(){
        return keylist;
    }

    public int size(){
        return json.size();
    }

    public void clear(){
        json.clear();
        keylist.clear();
    }

    public JSONObject getJson() {
        return json;
    }
}
